package self.cloud.domain.aliyun.handler;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import self.cloud.domain.aliyun.entity.AliyunDomain;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
public class AliyunDomainHandler {
    private static final Logger logger = LoggerFactory.getLogger(AliyunDomainHandler.class);

    @Autowired
    IAcsClient acsDomainClient;

    @Autowired
    DescribeDomainsRequest domainRequest;

    @Autowired
    public List<AliyunDomain> findAll() {
        logger.debug("method findAll");
        List<AliyunDomain> aliyunDomains = new ArrayList<>();

        DescribeDomainsResponse response;

        try {
            logger.debug(String.valueOf(System.nanoTime()));
            response = this.acsDomainClient.getAcsResponse(this.domainRequest);
            logger.debug(String.valueOf(System.nanoTime()));

            for (DescribeDomainsResponse.Domain domain : response.getDomains()) {
                aliyunDomains.add(new AliyunDomain(domain));
            }
        } catch (ClientException e) {
            logger.error(e.toString(), e);
        }

        return aliyunDomains;
    }

    // todo: use Optional
    public AliyunDomain findByName(String name) {
        logger.debug("method findByName [domainName]:{}", name);

        if (name == null || name.equals("")) {
            throw new NullPointerException("name cannot null or empty");
        }

        List<AliyunDomain> domains = this.findAll();
        logger.debug("[domains.count]:{}", domains.size());

        for (AliyunDomain domain : domains) {
            if (domain.getName().equals(name)) {
                return domain;
            }
        }

        return null;
    }

}
